var mapformid="mapstate";
var tabpref="";
var geocoder;
var map;
var m_projection;
var m_latlng=new google.maps.LatLng(50.4501,30.5234); //kiev
var m_levels=[5,7,10,12,15,];
var m_myOptions = {
    zoom: 10, //show all city
    center: m_latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
}
    
var m_bounds;
var m_rect;

var m_marker=null;
var show_add_marker=false;

var markersArray = [];
var infowindow;

if (typeof(Number.prototype.toRad) === "undefined") {
    Number.prototype.toRad = function() {
        return this * Math.PI / 180;
    }
}

function calcDistance(lat1, lon1, lat2, lon2)
{
    var R = 6371; // km
    var dLat = (lat2-lat1).toRad();
    var dLon = (lon2-lon1).toRad();
    var lat1 = lat1.toRad();
    var lat2 = lat2.toRad();

    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var d = R * c;
    return d;
}
//$("#advs table tbody tr td:first-child div input").each(function (i){})
function parseTable()
{
    deleteOverlays();
    
    var tds=$("#advs table tbody tr td:first-child div input");
    var img=$("#advs table tbody tr td:first-child div img");
    var content=$("#advs table tbody tr td:nth-child(2) div");
    var j=0
    for (var i=0;i<tds.length;i+=2)
    {
        var lat=new Number(tds[i].value);
        var lng=new Number(tds[i+1].value);
        var latlng=new google.maps.LatLng(lat,lng);
        var url=img[j].src;
        addMarker(latlng, url, content[j].innerHTML);
        j++
    }

}


function addMarker(location, imageurl, html) {
    var options={
        position: location,
        map: map
    }
    if(!(imageurl==undefined)) options.icon=imageurl;
    var marker = new google.maps.Marker(options);
    markersArray.push(marker);
    if(!(html==undefined)) {
        
        windows[marker.__gm_id]={
            html:html
        };
        var i=markersArray.length-1;
        google.maps.event.addListener(marker, 'click', function(){
            infowindow.close();
            infowindow.setContent(html);
            infowindow.open(map,markersArray[i]);
        });
        google.maps.event.addListener(marker, 'mouseover', function(){
            //infowindow.setContent(html);
            //infowindow.open(map,markersArray[i]);
            var scale = Math.pow(2, map.getZoom());
            var nw = new google.maps.LatLng(
                map.getBounds().getNorthEast().lat(),
                map.getBounds().getSouthWest().lng()
                );
            var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
            var worldCoordinate = map.getProjection().fromLatLngToPoint(marker.getPosition());
            var pixelOffset = new google.maps.Point(
                Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale),
                Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)
                );
            
            //var point=map.getProjection().fromLatLngToPoint(markersArray[i].getPosition());
            var mtop=$("#map_canvas").offset().top;
            var mleft=$("#map_canvas").offset().left; 
            //$("#showitemblock").css("top",point.y+mtop);
            //$("#showitemblock").css("left",point.x+mleft);
            $("#showitemblock").css("top",mtop+pixelOffset.y);
            $("#showitemblock").css("left",mleft+pixelOffset.x);
            $("#showitemblock").html(html);
            $("#showitemblock").css("display","");
        });
        google.maps.event.addListener(marker, 'mouseout', function(){
            $("#showitemblock").css("display","none");
        });
    }
}
function removeMarker(marker)
{
    markersArray.pop(marker);
    marker.setMap(null);
    windows[marker.__gm_id]={}
}

function registerMarker(marker){
    markersArray.push(marker);
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
    if (markersArray) {
        for (var i=0;i< markersArray.length;i++) {
            markersArray[i].setMap(null);
        }
    }
}

// Shows any overlays currently in the array
function showOverlays() {
    if (markersArray) {
        for (var i=0;i< markersArray.length;i++) {
            markersArray[i].setMap(map);
        }
    }
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
    if (markersArray) {
        for (var i=0;i< markersArray.length;i++) {
            markersArray[i].setMap(null);
        }
        markersArray=[];
        windows={}
    }
}

function setZoomSelector(){
    var z= map.getZoom();
    var bounds=map.getBounds();
    m_bounds=bounds;
    var center=map.getCenter();
    document.getElementById(mapformid+":zoom").value=z;
    document.getElementById(mapformid+":lat").value=center.lat();
    document.getElementById(mapformid+":lng").value=center.lng();
    document.getElementById(mapformid+":lats").value=bounds.getSouthWest().lat();
    document.getElementById(mapformid+":lngw").value=bounds.getSouthWest().lng();
    document.getElementById(mapformid+":latn").value=bounds.getNorthEast().lat();
    document.getElementById(mapformid+":lnge").value=bounds.getNorthEast().lng();
    var lat1=bounds.getSouthWest().lat();
    var lat2=bounds.getNorthEast().lat();
    var lng1=bounds.getSouthWest().lng();
    var lng2=bounds.getNorthEast().lng();
    if(getInternetExplorerVersion()==-1){
        document.getElementById("rangex").innerHTML=Math.floor(calcDistance(lat1,lng1,lat1,lng2));
        document.getElementById("rangey").innerHTML=Math.floor(calcDistance(lat1,lng1,lat2,lng1));
    }
    else
    {
        if(document.getElementById("rangey"))        
            document.getElementById("rangey").parentNode.innerHTML="";    
        document.getElementById("rangex").innerHTML=Math.floor(calcDistance(lat1,lng1,lat1,lng2))+" x "+ Math.floor(calcDistance(lat1,lng1,lat2,lng1));
    }
    // init area selector
    m_rect.setBounds(m_bounds);

// updateGeoTag();
    
}
//copies map bounds to form
//assume lats, latn, lnge,lngw
function getCurrentBounds(formName)
{
    var bounds=map.getBounds();
    document.getElementById(tabpref+formName+"zoom").value=map.getZoom();
    document.getElementById(tabpref+formName+"lats").value=bounds.getSouthWest().lat();
    document.getElementById(tabpref+formName+"lngw").value=bounds.getSouthWest().lng();
    document.getElementById(tabpref+formName+"latn").value=bounds.getNorthEast().lat();
    document.getElementById(tabpref+formName+"lnge").value=bounds.getNorthEast().lng();
}
var m_zoom;
var m_listener;
function setMapBounds(formName)
{
    m_zoom=document.getElementById(tabpref+formName+"zoom").value;
    var lats=document.getElementById(tabpref+formName+"lats").value;
    var lngw=document.getElementById(tabpref+formName+"lngw").value;
    var sw=new google.maps.LatLng(lats, lngw, true); 
    var latn=document.getElementById(tabpref+formName+"latn").value;
    var lnge=document.getElementById(tabpref+formName+"lnge").value;
    var ne=new google.maps.LatLng(latn, lnge, true);
    var bounds=new google.maps.LatLngBounds(sw,ne);
    map.fitBounds(bounds);
    m_listener = google.maps.event.addListener(map, "idle", function() { 
        map.setZoom(Number(m_zoom));
        google.maps.event.removeListener(m_listener); 
    });
    
}
function setMapCenter(lat,lng)
{
    var latlng=new google.maps.LatLng(lat, lng, true); 
    map.setCenter(latlng);

}
function setMarkerPosition(lat,lng)
{
    var latlng=new google.maps.LatLng(lat, lng, true); 
    m_marker.setPosition(latlng);
}


function changeZoom(obj, event)
{
    
    map.setZoom(parseInt(obj.value));
    return true;
}

function setLatLng(latlng,address){
    var lat=document.getElementById(mapformid+":lat");
    var lng=document.getElementById(mapformid+":lng");
    var adr=document.getElementById(mapformid+":address");
    lat.value=latlng.lat();
    lng.value=latlng.lng();
    if(address!=undefined)
        adr.value=address;
// adr.onchange();
    
}

function updateGeoTag(){
    var btn=document.getElementById(mapformid+":update");
    btn.onclick();
}
function updateMarker(){
    if(show_add_marker==true && m_marker==null) 
        m_marker= new google.maps.Marker({
            map: map,
            draggable:true,
            position: map.getCenter()
        });           
    if(m_marker!=null)
    {
        m_marker.setPosition(map.getCenter());
        updateMarkerPosition(map.getCenter());
        google.maps.event.addListener(m_marker, 'click', function() {
            infowindow.open(map,m_marker);
            geocodePosition(m_marker.getPosition());
        });
        google.maps.event.addListener(m_marker, 'dragend', function() {
            geocodePosition(m_marker.getPosition());
        });
    }
}
function initialize() {
    mapformid=$(".mapsate").attr("id");
    tabpref=mapformid.substr(0,mapformid.indexOf(":",0));
    if(tabpref.length>0) tabpref+=":";
    
    geocoder = new google.maps.Geocoder();
    
    map = new google.maps.Map(document.getElementById("map_canvas"), m_myOptions);
    google.maps.event.addListener(map, 'bounds_changed',setZoomSelector);
    m_bounds=map.getBounds();
    infowindow=new google.maps.InfoWindow({});
    m_rect=new google.maps.Rectangle({
        map:map,
        bounds:m_bounds,
        fillOpacity:0,
        strokeColor:"gray"
    });
    updateMarker();
// Update current position info.
//  updateMarkerPosition(latLng);
//  geocodePosition(latLng);

}

function geocodePosition(pos) {
    geocoder.geocode({
        latLng: pos
    }, function(responses) {
        if (responses && responses.length > 0) {
            updateMarkerAddress(responses[0].formatted_address);
            updateMarkerPosition(m_marker.getPosition());
        } else {
            updateMarkerAddress('Cannot determine address at this location.');
            updateMarkerPosition(m_marker.getPosition());
        }
    });
}

function geocodeAddress(adr) {
    geocoder.geocode({
        address: adr
    }, function(responses) {
        if(m_marker!=null){ 
            if (responses && responses.length > 0) {
            
                m_marker.setPosition(responses[0].geometry.location);
                map.setCenter(m_marker.getPosition());
                updateMarkerAddress(responses[0].formatted_address);
                updateMarkerPosition(m_marker.getPosition());
            }else {
                updateMarkerAddress('Cannot determine address at this location.');
                updateMarkerPosition(m_marker.getPosition());
            }
        }
        else
        {
            if (responses && responses.length > 0) {
                map.setCenter(responses[0].geometry.location);
            }
        }
    }
    );
}


function updateMarkerPosition(latLng) {
    document.getElementById('lat').value =latLng.lat();
    document.getElementById('lng').value =latLng.lng();
}

function updateMarkerAddress(str) {
    infowindow.setContent(str);
    document.getElementById('address').value = str;
}

 
  
  



function codeAddressButton() {
    updateMarker();
    var address = document.getElementById("show_on_map:address_input").value;
    geocodeAddress(address);
    
}
function codeAddress(o,e) {
    updateMarker();
    var keycode;
    if(window.m_bounds==undefined) {
        m_bounds=map.getBounds();
    }

    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == 13)
    {
        var address = o.value;
        geocodeAddress(address);
    }
    else
        return true;
}

// old version
//function __OLDcodeAddress(o,e) {
//    updateMarker();
//    var keycode;
//    if(window.m_bounds==undefined) {
//        m_bounds=map.getBounds();
//    }
//
//    if (window.event) keycode = window.event.keyCode;
//    else if (e) keycode = e.which;
//    else return true;
//    if (keycode == 13)
//    {
//        var address = o.value;
//        geocoder.geocode( {
//            'address': address, 
//            'bounds':m_bounds, 
//            'region':'UA'
//        }, function(results, status) {
//            if (status == google.maps.GeocoderStatus.OK) {
//                map.setCenter(results[0].geometry.location);
//                var marker = new google.maps.Marker({
//                    map: map,
//                    draggable:true,
//                    position: results[0].geometry.location
//        
//                });
//                
//                infowindow = new google.maps.InfoWindow({
//                    content: results[0].formatted_address + " "+ results[0].geometry.location.toString()
//                });
//                google.maps.event.addListener(marker, 'click', function(){
//                    infowindow.open(map,marker);
//                });
//                google.maps.event.addListener(marker, 'draged', function(){
//                    setLatLng(marker.getPosition(),marker.getPosition().toString());
//                    
//                });
//    
//            //google.maps.event.addListener(marker, 'drag', function(){infowindow.open(map,marker);});
//            } else {
//                alert("Geocode was not successful for the following reason: " + status);
//            }
//        });
//
//    }
//    else
//        return true;
//}

//var location_list, location_idx=0;
//var location_timer=0;
//
//function geocode()
//{
//    if(location_idx>=location_list.length)
//    {
//        clearTimeout(location_timer);
//        location_idx=0;
//        return;
//    }
//    var text =location_list[location_idx].innerHTML;
//    geocoder.geocode( {
//        'address': text, 
//        'bounds':m_bounds, 
//        'region':'UA'
//    }, function(results, status) {
//        if (status == google.maps.GeocoderStatus.OK) {
//            map.setCenter(results[0].geometry.location);
//            //            var marker = new google.maps.Marker({
//            //                map: map,
//            //                position: results[0].geometry.location
//            //        
//            //            });
//            setLatLng(results[0].geometry.location,text);
//            updateGeoTag();
//            //registerMarker(marker);
//            location_list[location_idx].innerHTML+=" "+results[0].geometry.location.toString();
//                
//        //google.maps.event.addListener(marker, 'click', function(){
//        //    infowindow.open(map,marker);
//        //});
//        // google.maps.event.addListener(marker, 'drag', function(){
//        //    setLatLng(marker.getPosition());
//                    
//        //});
//    
//        //google.maps.event.addListener(marker, 'drag', function(){infowindow.open(map,marker);});
//        } else {
//            if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT)
//            {
//                location_idx--;    
//            }
//            else
//            if (status == google.maps.GeocoderStatus.ZERO_RESULTS)   { 
//                location_list[location_idx].innerHTML+=" not found";
//            }
//            else 
//            {
//                location_list[location_idx].innerHTML+=" Error...";
//            }
//    
//        }
//        location_idx++;    
//    });
//}
//
//function startgeocode()
//{
//    location_list=$("td");
//    location_timer=setInterval("geocode()",1000,3000);
//}
initArray.push(initialize);  